//
//  SISSMessageRecommendViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/6/28.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSMessageRecommendViewController.h"
#import "SISSComboBoxView.h"
#import "SISSRecommandHouseCell.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"
#import "SISSHouseResourceDetailVC.h"

static NSString *recommendHouseCellID = @"recommendHouseCellID";
@interface SISSMessageRecommendViewController ()<UITableViewDelegate,UITableViewDataSource,SISSComboBoxViewDelegate,SISSRecommandHouseCellDelegate>

/* 推荐客源视图 */
@property (weak, nonatomic) SISSMessagePassengerReccommendViewController *reccommendPassengerViewController;
@property (weak, nonatomic) SISSMessageRentOutRecommendViewController *reccommendrentOutViewController;
@property (weak, nonatomic) SISSMessageTenantRecommendViewController *reccommendTenantViewController;
/** 筛选视图 */
@property (weak, nonatomic) SISSComboBoxView *filterView;
/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/** 房源数组 */
@property (copy, nonatomic) NSArray<SISSHouseResourceModel *> *houseResourceArr;

/* 底部推荐按钮 */
@property (weak, nonatomic) UIButton *recommendButton;

/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** pageNo */
@property (assign, nonatomic) NSInteger pageNo;

/* selectIndexPath */
@property (assign, nonatomic) NSIndexPath *selectIndexPath;

@end

@implementation SISSMessageRecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestEntrustHouseResourceData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
    [self.reccommendPassengerViewController.filterView.comBoBoxView dismissPopView];
    [self.reccommendrentOutViewController.filterView.comBoBoxView dismissPopView];
    [self.reccommendTenantViewController.filterView.comBoBoxView dismissPopView];
}

#pragma mark - SISSComboBoxViewDelegate
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"售价"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    
    [self requestEntrustHouseResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    
    [self requestEntrustHouseResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = subtitles;
    }
    
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    [self requestEntrustHouseResourceData];
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}


#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.houseResourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSRecommandHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:recommendHouseCellID];
    cell.delegate = self;
    cell.isChooseMain = YES;
    cell.houseResourceModel = self.houseResourceArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SISSHouseResourceDetailVC *vc = [[SISSHouseResourceDetailVC alloc] init];
    vc.title = @"房源详情";
    vc.isHideBottomButton = YES;
    SISSHouseResourceModel *houseModel = self.houseResourceArr[indexPath.row];
    vc.houseResourceModel = houseModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SISSRecommandHouseCellDelegate
- (BOOL)recommandHouseResourceCell:(SISSRecommandHouseCell *)cell checkButtonIsSelected:(BOOL)isSelected {
    
    [self.recommendButton setBackgroundColor: isSelected ? COLOR(0x349DC5) : COLOR(0x8998A5)];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    self.houseResourceArr[self.selectIndexPath.row].isSelected = NO;
    self.houseResourceArr[indexPath.row].isSelected = YES;
    self.selectIndexPath = indexPath;
    
    [self.tableView reloadData];
    return NO;
}

#pragma mark - 推荐按钮点击事件
- (void)recommendButtonClickAction {
    
    if (!self.selectIndexPath) return;
    if (self.recommendHouseBlock) {
        self.recommendHouseBlock(self.houseResourceArr[self.selectIndexPath.row]);
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 2.2.1 已委托房源的请求
- (void)requestEntrustHouseResourceData{
    
    // 非空处理
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };
    
    [kJsonRequestNetworkingManager requestEntrustHouseResourceWithParameters:parameters success:^(NSArray<SISSHouseResourceModel *> *houseResources) {
        
        //        if (self.houseResourceArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
        //
        //            [self.houseResourceArr removeAllObjects];
        //        }
        //
        //        for (int i = 0; i < houseResources.count; i++) {
        //
        //            [self.houseResourceArr addObject:houseResources[i]];
        //        }
        self.houseResourceArr = houseResources;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
        
        
    } failed:^(NSError *error) {
        
        
    }];
}

- (void)clickBackItemAction {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - NavigationItems
- (void)setupNavigationItems {
    [super setupNavigationItems];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackItemAction)];
    
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"房源", @"客源", @"出租", @"租客"]];
    segmentControl.selectedSegmentIndex = 0;
    segmentControl.tintColor = COLOR(0x249DC5);
    [segmentControl addTarget:self action:@selector(segmentControlbutClick:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentControl;
}

#pragma mark - UI
- (void)setupSubviews {
    
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:YES isCooperation:NO];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerNib:[UINib nibWithNibName:@"SISSRecommandHouseCell" bundle:nil] forCellReuseIdentifier:recommendHouseCellID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 推荐
    UIButton *recommendButton = [[UIButton alloc] init];
    [recommendButton setTitle:@"推荐" forState:UIControlStateNormal];
    [recommendButton setBackgroundColor:COLOR(0x8998A5)];
    [recommendButton addTarget:self action:@selector(recommendButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:recommendButton];
    self.recommendButton = recommendButton;
    
    // 自动布局
    
    CGFloat recommendButtonHeight = 47;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.filterView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(recommendButton.mas_top);
    }];
    
    [recommendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(recommendButtonHeight);
    }];
    
    // 添加推荐客源
    SISSMessagePassengerReccommendViewController *reccommendPassengerViewController = [[SISSMessagePassengerReccommendViewController alloc] init];
    reccommendPassengerViewController.navigationHeight = NAVIGATION_HEIGHT;
    [self.view addSubview:reccommendPassengerViewController.view];
    [self addChildViewController:reccommendPassengerViewController];
    [reccommendPassengerViewController didMoveToParentViewController:self];
    [reccommendPassengerViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.reccommendPassengerViewController = reccommendPassengerViewController;
    self.reccommendPassengerViewController.view.hidden = YES;
    self.reccommendPassengerViewController.recommendBlock = ^(SISSPassengerResourceModel *passengerModel) {
        
        if (self.recommendPassengerBlock) {
            self.recommendPassengerBlock(passengerModel);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    };
    
    // 添加推荐出租
    SISSMessageRentOutRecommendViewController *reccommendrentOutViewController = [[SISSMessageRentOutRecommendViewController alloc] init];
    
    [self.view addSubview:reccommendrentOutViewController.view];
    [self addChildViewController:reccommendrentOutViewController];
    [reccommendrentOutViewController didMoveToParentViewController:self];
    [reccommendrentOutViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.reccommendrentOutViewController = reccommendrentOutViewController;
    self.reccommendrentOutViewController.view.hidden = YES;
    self.reccommendrentOutViewController.recommendBlock = ^(SISSRentOutModel *rentOutModel) {
        if (self.recommendRentOutBlock) {
            self.recommendRentOutBlock(rentOutModel);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    };
    
    // 添加推荐租客
    SISSMessageTenantRecommendViewController *reccommendTenantViewController = [[SISSMessageTenantRecommendViewController alloc] init];
    [self.view addSubview:reccommendTenantViewController.view];
    [self addChildViewController:reccommendTenantViewController];
    [reccommendTenantViewController didMoveToParentViewController:self];
    [reccommendTenantViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.reccommendTenantViewController = reccommendTenantViewController;
    self.reccommendTenantViewController.view.hidden = YES;
    self.reccommendTenantViewController.recommendBlock = ^(SISSTenantModel *tenantModel) {
        if (self.recommendTenantBlock) {
            self.recommendTenantBlock(tenantModel);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}

#pragma mark - segmentControl点击事件
- (void)segmentControlbutClick:(UISegmentedControl *)sender {
    
    self.reccommendPassengerViewController.view.hidden = sender.selectedSegmentIndex != 1;
    self.reccommendrentOutViewController.view.hidden = sender.selectedSegmentIndex != 2;
    self.reccommendTenantViewController.view.hidden = sender.selectedSegmentIndex != 3;
    [self.filterView.comBoBoxView dismissPopView];
    [self.reccommendPassengerViewController.filterView.comBoBoxView dismissPopView];
    [self.reccommendrentOutViewController.filterView.comBoBoxView dismissPopView];
    [self.reccommendTenantViewController.filterView.comBoBoxView dismissPopView];
    
}


#pragma mark - Getter & Setter
- (NSArray<SISSHouseResourceModel *> *)houseResourceArr {
    if (!_houseResourceArr) {
        _houseResourceArr = [NSArray array];
    }
    return _houseResourceArr;
}


- (NSArray *)area {
    
    if (!_area) {
        _area = [NSArray array];
    }
    return _area;
}



- (NSArray *)direction {
    
    if (!_direction) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    
    if (!_decoration) {
        _decoration = [NSArray array];
    }
    return _decoration;
}

@end
